package com.dangf.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateTemplate;

import com.dangf.dao.BaseDao;
import com.dangf.utils.GenericsUtils;

/**
 * 泛型Dao，增删查改底层
 * @author Hello_海生
 * @date 2015年2月2日
 * @param <T>
 */
@SuppressWarnings("unchecked")
public class BaseDaoImpl<T> implements BaseDao<T> {
	@Resource(name = "hibernateTemplate")
	protected HibernateTemplate hibernateTemplate;

	// 获取session
	protected Session getSession() { 
		return hibernateTemplate.getSessionFactory().getCurrentSession();
	}
		
	protected Class<T> clazz;	//对象类
	public BaseDaoImpl() {
		clazz = GenericsUtils.getSuperClassGenricType(this.getClass(), 0);
		System.out.println("初始化"+this.clazz.getName()+"DAO");
	}
	
	@Override
	public Serializable save(T entity) {
		return this.hibernateTemplate.save(entity);
	}
	
	@Override
	public void deleteById(Serializable id) {
		T t = this.getEntityById(id);
		this.hibernateTemplate.delete(t);
	}

	@Override
	public void deleteAll(List<T> list) {
		this.hibernateTemplate.deleteAll(list);
	}

	@Override
	public T getEntityById(Serializable id) {
		return this.hibernateTemplate.get(clazz, id);
	}
	
	@Override	//根据某项参数查询 列表
	public List<T> getEntityListByParams(String s,Object params) {
		List <?> list = this.hibernateTemplate.findByNamedParam("from "+clazz.getName()+" where "+s+" = :params", "params", params);
		return (List<T>)list;
	}
	
	@Override	//根据某项参数查询 列表
	public T getEntityByParams(String s,Object params) {
		List <?> list = this.hibernateTemplate.findByNamedParam("from "+clazz.getName()+" where "+s+" = :params", "params", params);
		if(list.size()>0)return (T) list.get(0);
		return null;
	}

	@Override
	public List<T> getAll() {
		return this.hibernateTemplate.loadAll(clazz);
	}
	
	
	@Override	//查询分页
	public List<T> getListByPage(int start,int count){  
        Criteria criteria = this.getSession().createCriteria(clazz);  
        criteria.setFirstResult(start);  
        criteria.setMaxResults(count);  
        return criteria.list();
	}

	@Override
	public void update(T entity) {
		this.hibernateTemplate.update(entity);
	}

	@Override
	public void saveOrUpdate(T entity) {
		this.hibernateTemplate.saveOrUpdate(entity);
	}

	@Override
	public void saveOrUpdateAll(List<T> list) {
		for (int i = 0; i < list.size(); i++) {
			this.saveOrUpdate(list.get(i));
			//每二十次清空一次 Session
			if(i%20 == 0){
				this.getSession().flush();
				this.getSession().clear();
			}
		}
	}

}
